/**
 * 
 */
package edu.scu.lijobs.android;



import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import edu.scu.lijobs.android.R;
import edu.scu.lijobs.android.R.layout;
import com.google.android.gcm.GCMRegistrar;
import com.google.code.linkedinapi.client.JobsApiClient;
import com.google.code.linkedinapi.client.Parameter;
import com.google.code.linkedinapi.client.enumeration.JobField;
import com.google.code.linkedinapi.client.enumeration.SearchParameter;
import com.google.code.linkedinapi.schema.Company;
import com.google.code.linkedinapi.schema.FacetType;
import com.google.code.linkedinapi.schema.Job;
import com.google.code.linkedinapi.schema.Jobs;

import static edu.scu.lijobs.android.GCMManager.*;
public class TabJobResultsFragment extends Fragment {
	
	
	AsyncTask<Void, Void, Void> mRegisterTask;
	
	private JobResultRowAdapter adapter;
	
	
	private List<Job> jobs;

	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
         
            return null;
        }
		jobs = new ArrayList<Job>();
		
		LinearLayout toReturn =  (LinearLayout)inflater.inflate(layout.tab_job_results_layout, container, false);
		
		ListView listView = (ListView) toReturn.findViewById(R.id.jobresultListView);
		// First paramenter - Context
				// Second parameter - Layout for the row
				// Third parameter - ID of the TextView to which the data is written
				// Forth - the Array of data
		
		 adapter = new JobResultRowAdapter(getActivity(),jobs);
//		 View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
//	        listView1.addHeaderView(header);
		// Assign adapter to ListView
		listView.setAdapter(adapter); 
//		searchJobs();
		
       UiHelper.jobResultsFragment = this;
        return toReturn;
        
        
        
		
		
	}
	
	

	@Override
	public void onDestroyView() {
		if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        getActivity().unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(this.getActivity());
		super.onDestroyView();
	}


    private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(
                    getString(R.string.error_config, name));
        }
    }

   
	
	
	
	 private final BroadcastReceiver mHandleMessageReceiver =
	            new BroadcastReceiver() {
	        @Override
	        
	        public void onReceive(Context context, Intent intent) {
	            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
	            System.out.println("NEW MESSAGE");
	            searchJobs();
	        }
	    };
	    
	    public List<Job> getJobs() {
			return jobs;
		}
		  
	    public void findJob( final String jobIds) {
	    	new Thread() {
	    		public void run() {
	    			try {
	    				String[] jobIdArray = jobIds.split(",");
	    				for(int i = jobIdArray.length-1; i >=0; i--) {
	    					String jobId = jobIdArray[i];
	    					JobsApiClient jobsApiClient = LinkedInApiManager.getInstance().getJobsApiClient();
		    				Job job = jobsApiClient.getJobById(jobId, EnumSet.allOf(JobField.class));
		    				job.setCompany(LinkedInApiManager.getInstance().getCompany(job.getCompany().getId()));
		    				getJobs().add(0,job);
		    				if(getJobs().size()>= 20) {
		    					getJobs().remove(getJobs().get(getJobs().size()-1));
		    				}
	    				}
	    				getActivity().runOnUiThread(new Runnable() {//updating UI thread from different thread not a good idea...
	                         public void run() {
	                        	 adapter.notifyDataSetChanged();
	                        	 GCMIntentService.generateNotification(UiHelper.jobResultsFragment.getActivity(), "New Jobs Found!!");
	                         }
	                     });
	    				
	        			 
	    			} catch(Exception e) {
	    				e.printStackTrace();
	    			}
	    			
	    		}
	    	}.start();
	    	
	    }
		public void searchJobs() {
	    	new Thread() {
	    		public void run() {
	    			try {
	    				
	    				JobsApiClient jobsApiClient = LinkedInApiManager.getInstance().getJobsApiClient();
	        			Map<SearchParameter,String> searchParameterMap = new HashMap<SearchParameter,String>();
	        			searchParameterMap.put(SearchParameter.JOB_TITLE, "Software Engineer");
	        			searchParameterMap.put(SearchParameter.COMPANY_NAME,"LinkedIn");
	        		
	        			searchParameterMap.put(SearchParameter.POSTAL_CODE, "94560");
	        			searchParameterMap.put(SearchParameter.COUNTRY_CODE, "us");
	        			searchParameterMap.put(SearchParameter.DISTANCE, "100");
	        			Jobs jobs = jobsApiClient.searchJobs(searchParameterMap, EnumSet.allOf(JobField.class),0,1);
	        			
	    		       	List<Job> jobList = jobs.getJobList();
	        			 for(Job job: jobList) {
	        				 
	        				Company company = LinkedInApiManager.getInstance().getCompany(job.getCompany().getId());
	            				job.setCompany(company);
	    		       		getJobs().add(job);
	    		       		
	    		       	 }
	        			 
	        			 
	                     getActivity().runOnUiThread(new Runnable() {//updating UI thread from different thread not a good idea...
	                         public void run() {
	                        	 adapter.notifyDataSetChanged();
	                         }
	                     });
	                     
	                     
	        			
	        			 
	    			} catch(Exception e) {
	    				e.printStackTrace();
	    			}
	    			
	    		}
	    	}.start();
	    	
	    }

	

}
